package com.suliao.common.core;

import cn.hutool.json.JSONUtil;
import com.suliao.common.annotation.LoginCheck;
import com.suliao.common.annotation.LoginPass;
import com.suliao.common.base.UserContext;
import com.suliao.common.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @author ：M1nG
 * @date ：Created in 2020/10/15 15:22
 * @description：  RedisSession 拦截器
 * @version: 1.0
 */
@Slf4j
public class RedisSessionInterceptor implements HandlerInterceptor {

    @Autowired
    private SessionUtil SessionUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Class clazz = handlerMethod.getMethod().getDeclaringClass();
        if (clazz.isAnnotationPresent(LoginPass.class) || method.isAnnotationPresent(LoginPass.class)) {
            return true;
        }
        LoginCheck loginCheck = null;
        if (method.isAnnotationPresent(LoginCheck.class)) {
            loginCheck = method.getAnnotation(LoginCheck.class);
        }
        if (clazz.isAnnotationPresent(LoginCheck.class)) {
            loginCheck = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(LoginCheck.class);
        }

        if (loginCheck != null && loginCheck.required()) {
            HttpSession session = request.getSession();
            if (session == null) {
                // request.getRequestDispatcher("/login/" + request.getRequestURI()).forward(request, response);
                response.sendRedirect("/login/" + request.getRequestURI());
            }
            UserContext userContext = SessionUtil.getUserContext(session);
            //todo  拿到userContext后的校验
            /*if (403 == 403) {
                String msg = URLUtil.encode("非法访问");
                response.sendRedirect("/error/403/"+msg);
            }*/
        }

        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
